<?php
/**
 * 自定义表单
 *
 * @package         YDCMS
 * @author          QQ:644157559 <644157559@qq.com>
 * @version         $Id: DiyFormModel.class.php v1.0 2014-06-12 17:27:03 $
 */

namespace Admin\Model;
class DiyFormModel extends CommonModel{
    /**
     * 自动验证
     * @var type 
     */
    protected $_validate = array(
        //array(验证字段1,验证规则,错误提示,[验证条件,附加规则,验证时间]),
        array("formname", "require", "表单名称必须填写！", 1),
        array("formname", "", "表单名称不能重复！", 0, "unique", 1),
        array("formtable", "require", "表单数据表必须填写！", 1, "regex", 1),
        array("formtable", "", "表单数据表重复！", 0, "unique", 1),
        array("formtable", "isTableName", "表单数据表名称不合法！", 1, "callback", 1),
        array("formtable", "checkTable", "表单数据表已存在！", 1, "callback", 1),
    );
    
    /**
     * 自动完成
     * @var type 
     */
    protected $_auto = array(
        array("subtime", "time", 1, "function")
    );
    
    /**
     * 检查表是否存在
     * @param type $table
     * @return boolean
     */
    public function checkTable($table) {
        $query = "SHOW TABLES FROM ". C("DB_NAME");
        $tables = $this->query($query);
        foreach ($tables as $val) {
            $row = array_values($val);
            if(empty($row[0])){
                 $row[0] = '';
            }
            if(C("DB_PREFIX") . $table == $row[0]){
                return false;
            }
        }
        return true;
    }
    
    /**
     * 判断表名是否合法
     * @param string|array $table 表名
     * @return BOOL
     */
    public function isTableName($table) {
        return $this->isItemName($table, '/^[a-zA-Z][a-zA-Z0-9_]{0,63}$/');
    }
    
    /**
     * 判断字段是否存在
     * @param type $table
     * @param type $field
     * @return type
     */
    function fieldExists($table, $field) {
        if (!($this->isTableName($table) && $this->isFieldName($field))){
            return -1;
        }
        if ($this->checkTable($table)){
            die(sprintf('Table \'%s\' is not exists.', $table));
        }
        $sql = 'SHOW COLUMNS FROM `' . $table . '` LIKE \'' . $field . '\'';
        $rs = $this->query($sql);
        return is_null($rs) ? false : true;
    }

    /**
     * 判断字段名是否合法
     * @param string $field
     * @return BOOL
     */
    public function isFieldName($field) {
        return $this->isTableName($field);
    }
}
